<template>
  <div class="voiceTOtext">
      <div class="navtitle">
          <span>实时语音转文本</span>
      </div>
      <div class="tit">
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  使用语音转文本（也称为语音识别）功能，可将音频流实时或脱机听录为文本。
      </div>
      
      <div class="woded">
          我的额度(单位:分钟)
      </div>
      <div class="edcontent">
          <div><span>额度：{{  quota }}        
</span>
         &nbsp;&nbsp;&nbsp;&nbsp; <span>已用:{{ usage }}</span></div>
          <!-- <a-button type="primary" >充值</a-button> -->
      </div>
      <div class="shiting">选择语言</div>
      <div>
          <a-select v-model:value="value" placeholder="请选择"  style="margin-right: 15px; width: 200px;" @change="changeSle">
            <a-select-option
              v-for="(item, index) in options"
              :key="index"
              :value="item.value">
              {{item.name}}
            </a-select-option>
          </a-select>

      </div>
      <div class="content">
          <div class="content-left">
              <div class="top">选择音频文件</div>
              <div class="box">
                  <!-- <p>将.WAV格式的音频文件(16kHz或者8kHz，16位和单声道PCM)文件上传</p> -->
                 <!-- <p> <a>浏览文件...</a></p> -->
                 <p><img src="/static/image/ht2.png" v-if="blnStarted" /> <img src="/static/image/ht1.png" v-else   /></p>
               <p>  <a href="javascript:void(0)" @click="getVoice()"><span v-if="!blnStarted">使用麦克风实时识别</span><span v-else >停止识别</span></a></p>
              </div>
          </div>
          <div class="content-right">
              <div class="top">识别结果</div>
              <div class="box">
                {{textData}}
              </div>
              <div style="text-align: right;margin-top:20px;"><a-button type="primary" @click="clear" >清空</a-button> <a-button type="primary" v-copy="textData">复制</a-button></div>
          </div>
      </div>
      <div class="helpVoice">
        <div class="titHelp">注意事项和建议</div>
        <div class="help_box">
          <p class="pL">点击开始识别的时候出现如下错误时，需要改变Chrome或者Edge浏览器的安全设置</p>
          <img src="/static/image/text4.png" />
          <p class="pL">方法如下:</p>
       
          <div class="item1">
            <p class="pL">新建一个标签页，在地址栏输入：chrome://flags/#unsafely-treat-insecure-origin-as-secure（此命令适用于Chrome和Edge）然后敲回车键打开设置。</p>
            <img src="/static/image/text1.png" />
          </div>
          <div class="item1">
            <p class="pL">按照下图的设置，将当前网页的地址部分，例如：http://xxx.xxx.com部分复制到，1号框里，同时改变2号位置的设置为Enabled。</p>
            <img src="/static/image/text2.png" />
          </div>
          <div class="item1">
            <p class="pL">改变设置以后，Chrome或者Edge浏览器右下角会出现一个【Relaunch】的按钮，点击这个按钮即可。或者关闭浏览器重新打开。</p>
            <img src="/static/image/text3.png" />
          </div>
          <a href="https://developer.aliyun.com/article/1139923" style="margin-bottom:30px;">参考链接： https://developer.aliyun.com/article/1139923</a>
        </div>
      </div>
  </div>
</template>
<script>
// import { ResultReason } from "microsoft-cognitiveservices-speech-sdk";
const speechsdk=window.SpeechSDK
console.log(speechsdk);
import {
getsubscription,updateusage,getvoicetotextlan,VoiceToTextGetusage

} from "@/api/index"

export default {
  data() {
    return {
      radio4: '1',
      textData:'',
      textarea:'',
      textarea1:'',
      blnStarted:false,
      options: [],
      value: '',
      subscriptionKey:'',
       serviceRegion:'',
       SpeechSDK :null,
       recognizer:null,
       timer:null,
       quota:'',
usage:'',

    }
  },
  methods:{
    clear(){
      this.textData=''
    },
    voiceToTextGetusage(){
      VoiceToTextGetusage().then(res=>{
       
       this.quota=res.data.quota
       this.usage=res.data.usage

      })
    },
   changeSle(value){
    console.log(value)
    
   },
    getSubscription(){
      getsubscription().then(res=>{
       
        this.subscriptionKey=res.data[0]
        this.serviceRegion=res.data[1]
      })
    },
    upDateusage(time){
      let data={
        lan:this.value,
        result:this.textData,
        time

      }
      updateusage(data).then(res=>{
        console.log(res)
      })
    },
    getVoicetotextlan(){
      getvoicetotextlan().then(res=>{
        this.options=res.data
      })
    },
    // getVoice(){
    //   console.log(22)
    // }
    async getVoice() {
      if(this.value==''){
        this.$message({
                  message: '请选择语言',
                  type: 'info'
              })
              return
      }
      // if(+this.quota-this.usage<=0){
      //   this.$message({
      //             message: '请充值',
      //             type: 'info'
      //         })
      //         return
      // }
       try {
       await getsubscription()
       } catch (error) {
        this.$message({
                  message: error.response.data.msg,
                  type: 'info'
              })
              return
 
       }
   
    // const tokenObj = await getTokenOrRefresh();
    // const speechConfig = speechsdk.SpeechConfig.fromAuthorizationToken(
    //   tokenObj.authToken,
    //   tokenObj.region
    // );
 
    var speechConfig = speechsdk.SpeechConfig.fromSubscription(
      this.subscriptionKey,
      this.serviceRegion
    );
    let that = this;
    speechConfig.speechRecognitionLanguage = this.value;
 
    const audioConfig = speechsdk.AudioConfig.fromDefaultMicrophoneInput();
   

    if (this.blnStarted) {
   
      this.recognizer.stopContinuousRecognitionAsync(
        function (result) {
          console.log("9999", result);
          that.blnStarted = false;
       
          that.recognizer.close();

          that.recognizer = undefined;
          clearInterval(that.timer);
        },
        function (err) {
          console.log(err);
          that.blnStarted = false;
        
          that.recognizer.close();
          that.recognizer = undefined;
        }
      );
      return false;
    } else {
      this.recognizer = new speechsdk.SpeechRecognizer(
        speechConfig,
        audioConfig
      );
      this.recognizer.recognized = function (item, result) {
      if (result?.privResult?.privText === undefined) return;
       
        that.upDateusage(result.result.privDuration)
        that.textData += result?.privResult?.privText;
      };
      this.recognizer.startContinuousRecognitionAsync(
        function (result) {
        
          console.log(result);
          // phraseDiv.innerHTML += "初始化成功";
          // startRecognizeOnceAsyncButton.innerHTML = "停止";
          that.blnStarted = true;
          // that.upDateusage(result.result.privDuration)
          // that.timer = setInterval(() => {
          //   //定时器开始
           
          // }, 60000);
        },
        function (err) {
          console.log(err);
          that.textData = err;
          window.console.log(err);

          that.recognizer.close();
          that.recognizer = undefined;
        }
      );
    }

  },
  },
 
mounted(){
      document.title = '语音转文本'
    this.getSubscription()
    this.getVoicetotextlan()
    this.voiceToTextGetusage()
  
   
  }
}
</script>
<style lang="less" scoped>
.voiceTOtext{
  padding: 30px;
  width: 1260px;
  max-width: 100%;
  margin: 0 auto;
  .box-center{
  margin-top:25px;
  .tip{
      display: inline-block;
      background: #fff;
      font-size: 14px;
      color:rgba(56,23,129,1);
      border-radius: 13px;
      border: solid 1px #707070;
     padding:5px 14px;
     margin-bottom: 10px;
     
  }

}

 .navtitle{
  padding-top:10px;
  padding-bottom: 15px;
  display: flex;
  align-items: center;
   span{
      font-size: 26px;
      font-weight: bold;
      color:rgba(56,23,129,1)
   }
   img{
      width: 14px;
      height: 24px;
      margin:0 5px;
   }
 }
 .tit{
  height: 132px;
  box-sizing: border-box;
  padding:20px 10px;
  background:#E9ECEF;
  font-size: 16px;;
  color:rgba(56,23,129,1);
  line-height: 28px;
  border-radius: 6px;
 }
 .woded{
  padding-top:10px;
  padding-bottom: 15px;
  font-size: 20px;;
  font-weight: bold;
  color:rgba(56,23,129,1);
 }
 .edcontent{
  width: 334px;
  height: 55px;
  display: inline-block;
  background: #E9ECEF;
  display: flex;
  align-items: center;
  padding:5px 5px 5px 10px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  border-radius: 6px;
  span{
      font-size: 16px;
      font-weight: bold;
      color:rgba(56,23,129,1);
      &.cz{

      }

  }
 }
 .shiting{
  font-size: 20px;;
  color:rgba(56,23,129,1);
  padding:7px;
  font-weight: bold;
 }
 .content{
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 30px;
  .top{
      font-size: 14px;
      font-weight: bold;
  }
  .content-left{
     
    
     .box{
      width: 418px;
      height: 271px;
      border: dashed 1px #707070;
      background: #F1F0EF;
     padding:30px 10px;
     box-sizing: border-box;
     text-align: center;
     overflow-y: scroll;
     /deep/.el-textarea .el-textarea__inner{
height:60px;
}
     }
      p{
          font-size: 20px;
          color: #000;
          margin-bottom: 15px;
          a{
              color: #4019E5;
          }
      }
  }
  .content-right{
    
    
      .box{
          width: 774px;
          height: 271px;
      border: solid 1px #707070;
      overflow-y: scroll;
      }
  }
 }
 .helpVoice{
  .titHelp{
    color:rgba(157,121,3,1);
    font-size: 14px;
    font-weight: bold;
  }
  .help_box{
    border: solid 1px #707070;
    margin:10px 0px;
    box-sizing: border-box;
    padding:5px 10px;
    padding-bottom:20px;
    .item1{
      background: #E9ECEF;
      padding:5px;
      margin-bottom: 15px;
      border-radius: 6px;

    }
    .pL{
      color:rgba(56,23,159,1);
      font-size: 16px;
      line-height: 24px;
      margin:5px 0px;
    }
    img{
      margin-bottom:10px;
    }
  }
 }
}
</style>